package com.br.android.widingwheels;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockActivity;
import com.br.android.widingwheels.adapter.ListLocaisAdapter;
import com.br.android.widingwheels.entidades.Local;

import fi.foyt.foursquare.api.FoursquareApi;
import fi.foyt.foursquare.api.FoursquareApiException;
import fi.foyt.foursquare.api.Result;
import fi.foyt.foursquare.api.entities.CompactVenue;
import fi.foyt.foursquare.api.entities.VenuesSearchResult;

public class ListaLocaisActivity extends SherlockActivity {

	private ListView listViewLocais;
	private ListLocaisAdapter adapter;

	private List<Local> listLocais;
	
	private ProgressDialog progressDialog;

	LocationManager lm;
	String melhorProvedor;
    Location location;
    String latitude;
    String longitude;

	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
//		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//		StrictMode.setThreadPolicy(policy); 
		
		setContentView(R.layout.layout_locais);
		
		

		listViewLocais = (ListView) findViewById(R.id.listViewLocais);
		listLocais = new ArrayList<Local>();
		
		lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		melhorProvedor = lm.getBestProvider(new Criteria(), true);
	    Location location = lm.getLastKnownLocation(melhorProvedor);
	    latitude = String.valueOf(location.getLatitude());
	    longitude = String.valueOf(location.getLongitude());

		progressDialog = ProgressDialog.show(this, "Widing Wheels", "Carregando lista com os locais, \n Aguarde...");
		carregaLista();
		
		
	    listViewLocais.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long longValue) {
				Local local = listLocais.get(position);
				Intent intent = new Intent();
				intent.putExtra("local", local.getNomeLocal());
				intent.putExtra("latitude", local.getLatitude());
				intent.putExtra("longitude", local.getLongitude());
				setResult(1, intent);
				finalizar();
			}
		});

	}

	
	public void carregaLista(){
		new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... params) {
			    String ll = latitude + ", " + longitude;
			    try {
					searchVenues(ll);
				} catch (FoursquareApiException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				adapter = new ListLocaisAdapter(ListaLocaisActivity.this, listLocais);
		        listViewLocais.setAdapter(adapter);
		        progressDialog.dismiss();
			}
			
		}.execute();
	}
	
	public void finalizar(){
		this.finish();
		overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
	}

	public void searchVenues(String ll) throws FoursquareApiException {
		// First we need a initialize FoursquareApi.
        FoursquareApi foursquareApi = new FoursquareApi("X5E0XJEKMLNMMR1ANLX23QSFVKIJAEFBGDXPF5CBSU5AWGGO",
        		"R51W2JOSDBGAU0DPLIRFIGUHY0ZN0MMHFT0CC44G3N3OKJ0V",
        		"http://appteste-androidapps.rhcloud.com/");

        // After client has been initialized we can make queries.
        Result<VenuesSearchResult> result =
        		foursquareApi.venuesSearch(ll, null, null, null, null, null, null, null, null, null, null);
        if (result.getMeta().getCode() == 200) {
          // if query was ok we can finally we do something with the data
          for (CompactVenue venue : result.getResult().getVenues()) {
        	   Local local = new Local();
        	   local.setNomeLocal(venue.getName());
        	   local.setEnderecoLocal(venue.getLocation().getAddress());
        	   local.setLatitude(venue.getLocation().getLat());
        	   local.setLongitude(venue.getLocation().getLng());
        	   listLocais.add(local);
          }
        } else {
          System.out.println("Error occured: ");
          System.out.println("  code: " + result.getMeta().getCode());
          System.out.println("  type: " + result.getMeta().getErrorType());
          System.out.println("  detail: " + result.getMeta().getErrorDetail());
        }
      }

}
